<template>
  <div class="user-center">
    <div class="center-container">
      <!-- 左侧固定菜单 -->
      <aside class="side-menu">
        <div class="menu-profile">
          <div class="avatar-wrapper">
            <img src="../assets/login/cart.jpg" alt="用户头像" class="avatar" />
            <div class="edit-avatar">
              <i class="iconfont icon-camera"></i>
            </div>
          </div>
          <h3 class="username">{{ nickName }}</h3>
          <p class="user-role">厦门大学</p>
          <p class="user-gender">
        <span class="gender-label">性别：</span>
        <span class="gender-value">{{ gender === 1 ? '男' : '女' }}</span>
      </p>
          <div class="user-level">
            <span class="level-tag">信用 A+</span>
            <span class="level-tag">已认证</span>
          </div>
          <!-- 新增余额信息 -->
          <div class="user-balance">
            <span class="balance-label">账户余额：</span>
            <span class="balance-value">¥{{money}}</span>
            <button class="recharge-btn" @click="goRecharge">充值</button>
          </div>
        </div>
        <div class="menu-list">
          <div class="menu-item active">
            <i class="iconfont icon-home"></i>
            <router-link to="/product" class="register-link">首页</router-link>
          </div>
       
          <div class="menu-item">
            <i class="iconfont icon-order"></i>
            <span>交易订单</span>
          </div>
          <div class="menu-item">
            <i class="iconfont icon-favorite"></i>
            <router-link to="/favorite" class="register-link">我的收藏</router-link>
          </div>
     
          <div class="menu-item">
            <i class="iconfont icon-settings"></i>
            <span @click="showChangePwdDialog = true">修改密码</span>
          </div>
          <!-- 新增退出登录项 -->
          <div class="menu-item" @click="handleLogout">
            <i class="iconfont icon-exit"></i>
            <span>退出登录</span>
          </div>
        </div>
      </aside>

      <!-- 右侧内容区 -->
      <main class="main-content">
     
    

        <!-- 最近交易记录 -->
        <div class="stats-grid">
    <div class="stat-card" v-for="(stat, index) in dashboardStats" :key="index">
      <div :class="['stat-icon', stat.iconClass]">
        <i :class="`iconfont ${stat.icon}`"></i>
      </div>
      <div class="stat-info">
        <span class="stat-value">{{ stat.value }}</span>
        <span class="stat-label">{{ stat.label }}</span>
      </div>
      <div class="stat-trend" :class="{ up: stat.trend > 0, down: stat.trend < 0 }">
        <span>{{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}%</span>
        <small>较上月</small>
      </div>
    </div>
  </div>

        <!-- 我的发布和收藏 -->
        <div class="two-column">
          <div class="section-card">
            <div class="card-header">
              <h2>我的发布</h2>
              <a class="more-link">查看全部</a>
            </div>
            <div class="goods-grid">
              <div class="goods-item" v-for="i in 4" :key="i">
                <div class="goods-img">
                  <img src="../assets/login/cart.jpg" />
                  <div class="goods-status">在售</div>
                </div>
                <div class="goods-info">
                  <h4>MacBook Pro 2022</h4>
                  <p class="goods-price">￥8999</p>
                </div>
              </div>
            </div>
          </div>
          <div class="section-card">
        <div class="card-header">
          <h2>我的收藏</h2>
          <a class="more-link">查看全部</a>
        </div>
        <div class="goods-grid">
          <!-- 遍历实际的收藏商品列表 -->
          <div class="goods-item" v-for="item in collectedGoods" :key="item.id">
            <div class="goods-img">
              <!-- 显示商品图片 -->
              <img @click="printGoodsIds(item.goodsId)" src="https://pic.nximg.cn/file/20230627/12561827_204342732109_2.jpg" alt="商品图片" />
              <div class="goods-status" :class="{ hot: item.isHot }">
                {{ item.isHot ? '抢手' : '' }}
              </div>
            </div>
            <div class="goods-info">
              <!-- 显示商品名称 -->
              <h4 >商品编号：{{ item.goodsId }}</h4>
             
            </div>
          </div>
        </div>
      </div>
        </div>
        <div class="card-header">
              <h2>我的订单</h2>
        
            </div>
        <div class="order-stats-grid">
  <div class="order-card" v-for="(orderItem, index) in orderGoods" :key="index">
    
    <div class="order-info-container">
      <span class="order-id">订单编号：{{ orderItem.orderId }}</span>
      
      <div class="order-meta-group">
        <span class="meta-label">商品编号：{{ orderItem.goodsId }}</span>
        <span class="meta-label">商品金额：{{ orderItem.price }}</span>
        <span class="meta-label status-label">商品状态：{{ orderItem.orderStatus }}</span>
        <span class="meta-label time-label">商品下单时间：{{ orderItem.orderTime }}</span>
      </div>
    
    </div>

  </div>

 
        
        </div>
      </main> 
    </div>
    <!-- 充值弹窗 -->
    <div v-if="dialogVisible" class="recharge-dialog">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>充值</h3>
          <button @click="dialogVisible = false" class="close-btn">&times;</button>
        </div>
        <div class="dialog-body">
          <label for="recharge-amount">充值金额：{{}}</label>
          <input 
            type="number" 
            id="recharge-amount" 
            v-model="rechargeAmount" 
            placeholder="请输入充值金额"
          />
        </div>
        <div class="dialog-footer">
          <button @click="dialogVisible = false" class="cancel-btn">取消</button>
          <button @click="handleRecharge" class="confirm-btn">确定</button>
        </div>
      </div>
    </div>
    <!-- 使用 Element Plus 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="充值"
      width="30%"
    >
      <el-form>
        <el-form-item label="充值金额">
          <el-input
            v-model="rechargeAmount"
            type="number"
            placeholder="请输入充值金额"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="showChangePwdDialog"
      title="修改密码"
      width="30%"
    >
      <el-form>
        <el-form-item label="旧密码">
          <el-input
            v-model="oldPassword"
            type="password"
            placeholder="请输入旧密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input
            v-model="newPassword"
            type="password"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input
            v-model="confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangePwdDialog = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>

import { ref,onMounted } from "vue";
import { useRouter } from "vue-router";
import { getUsers } from "../api/user";
import { getGoods } from '../api/good';
const gender = ref(0); // 性别，0=女，1=男
// 引入 Element Plus 组件
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElMessage , ElMessageBox} from 'element-plus';
// 控制对话框显示隐藏
const dialogVisible = ref(false);
// 充值金额
const rechargeAmount = ref('');
const router = useRouter();
const nickName = ref('');
const money = ref('');
const loading = ref(false);
const userId = localStorage.getItem('userId');
const id=userId
// 控制修改密码弹窗显示隐藏
const showChangePwdDialog = ref(false);
// 旧密码
const oldPassword = ref('');
// 新密码
const newPassword = ref('');
// 确认新密码
const confirmPassword = ref('');

// 存储收藏商品列表
const collectedGoods = ref([]);
const orderGoods = ref([]);
onMounted(() => {
  const  token =localStorage.getItem("accessToken")
  if (!token) {
    // 使用 ElMessageBox 替换 alert
    ElMessageBox.alert('请先登录', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
      showClose: false,
      customClass: 'exaggerated-alert',
      callback: () => {
        router.push("/");
      }
    });
  } else {
    test() // 页面加载时获取商品数据
    fetchCollectedGoods()
    fetchOrderGoods()
  }
  
})
// 新增获取收藏商品方法
const fetchCollectedGoods = async () => {
  try {
    const response = await getGoods.getCollectGoodsApi({ id });
    console.log(response)
    collectedGoods.value = response.data.data.list;
  } catch (error) {
    console.error('获取收藏商品失败:', error);
    ElMessage.error('获取收藏商品失败，请重试');
  }
};
// 新增获取订单商品方法
const fetchOrderGoods = async () => {
  try {
    const response = await getGoods.getOrderApi({userId});
    console.log(response.data.list)
    orderGoods.value = response.data.data.list;
  } catch (error) {
    console.error('获取收藏商品失败:', error);
    ElMessage.error('获取收藏商品失败，请重试');
  }
};


// 新增退出登录方法
const handleLogout = () => {
  // 清空所有本地缓存
  localStorage.clear();
  // 跳转到登录页面（请根据实际路由修改）
  router.push('/');
};
const printGoodsIds = (id) =>{

  console.log("商品编号列表：", id);
      localStorage.setItem("goodsId",id)
   
      router.push("/favoriteDetail");
    }
const goRecharge = () => {
  dialogVisible.value = true;
};

const handleRecharge = async () => {
  if (!rechargeAmount.value) {
    ElMessage.warning('请输入充值金额');
    return;
  }


    // 调用充值API
    const response = await getUsers.rechargeApi({
      id: userId,              
      amount: rechargeAmount.value 
    });

    if (response.data) {
      // 充值成功逻辑
      ElMessage.success(`成功充值 ${rechargeAmount.value} 元`);
      dialogVisible.value = false;
      rechargeAmount.value = '';
      test()
      // 可在此处添加刷新用户余额的逻辑
      // refreshUserBalance();
    } else {
      ElMessage.error('充值失败，请重试');
    }

};
// 处理修改密码逻辑
const handleChangePassword = async () => {
  if (!oldPassword.value || !newPassword.value || !confirmPassword.value) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  if (newPassword.value !== confirmPassword.value) {
    ElMessage.warning('两次输入的新密码不一致');
    return;
  }

  try {
    // 显示加载状态
    loading.value = true;
    
    // 调用修改密码API
    const response = await getUsers.changePasswordApi({
      userId: userId, // 从用户信息中获取用户ID
      currentPassword: oldPassword.value,
      password: newPassword.value
    });

    // 检查API响应
    if (response.data) {
      ElMessage.success('密码修改成功，请使用新密码登录');
      showChangePwdDialog.value = false;
      oldPassword.value = '';
      newPassword.value = '';
      confirmPassword.value = '';
      
      // 可以在这里添加自动登出逻辑
      // logout();
    } else {
      ElMessage.error('密码修改失败，请重试');
    }
  } catch (error) {
    console.error('修改密码出错:', error);
    
    // 处理特定错误情况
    if (axios.isAxiosError(error)) {
      if (error.response) {
        // 服务器返回错误状态码
        switch (error.response.status) {
          case 400:
            ElMessage.error('参数错误，请检查输入');
            break;
          case 401:
            ElMessage.error('当前密码不正确');
            break;
          case 403:
            ElMessage.error('权限不足，无法修改密码');
            break;
          default:
            ElMessage.error(`服务器错误: ${error.response.status}`);
        }
      } else if (error.request) {
        ElMessage.error('无法连接到服务器，请检查网络');
      } else {
        ElMessage.error('请求发送失败: ' + error.message);
      }
    } else {
      ElMessage.error('发生未知错误: ' + error.message);
    }
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};
const test = () => {
 
      getUsers.getUsersApi({
    userId: userId,
  })
    .then((response) => {
     console.log(response.data.data.nickname)
     nickName.value = response.data.data.nickname;
     money.value = response.data.data.experience; 
     gender.value =response.data.data.gender; 
    })

};
</script>
<style scoped>
   .menu-item:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
    
    .menu-item:active {
      background-color: rgba(0, 0, 0, 0.1);
    }
    
    /* 可以在这里添加全局样式 */
    :root {
      --primary-color: #1890ff;
      --text-color: #333;
      --hover-bg: rgba(0, 0, 0, 0.05);
      --active-bg: rgba(24, 144, 255, 0.1);
    }
/* 新增余额样式 */
.user-balance {
  display: flex;
  align-items: center;
  margin: 12px 0;
  padding: 8px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.balance-label {
  color: #666;
  font-size: 14px;
  margin-right: 8px;
}

.balance-value {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  margin-right: 12px;
}

.recharge-btn {
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 12px;
  padding: 4px 12px;
  font-size: 12px;
  cursor: pointer;
}

.recharge-btn:hover {
  background: #2563eb;
}
/* 退出登录菜单项样式（可根据现有样式调整） */
.menu-item.icon-exit {
  color: #ef4444; /* 红色退出图标 */
}

.menu-item.icon-exit:hover {
  background: #fee2e2; /* 鼠标悬停时浅红色背景 */
}
.user-center {
  min-height: 100vh;
  background: #f6f9fc;
  padding: 20px 40px;
}

.center-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  gap: 24px;
}

/* 左侧菜单样式 */
.side-menu {
  width: 240px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  position: sticky;
  top: 20px;
  height: fit-content;
}

.menu-profile {
  text-align: center;
  padding-bottom: 24px;
  border-bottom: 1px solid #eee;
  margin-bottom: 24px;
}

.avatar-wrapper {
  width: 100px;
  height: 100px;
  margin: 0 auto 16px;
  position: relative;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.edit-avatar {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: #3b82f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.username {
  font-size: 18px;
  margin-bottom: 4px;
}

.user-role {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.user-level {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.level-tag {
  padding: 4px 12px;
  background: #ebf5ff;
  color: #3b82f6;
  border-radius: 12px;
  font-size: 12px;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
  position: relative;
}

.menu-item i {
  font-size: 18px;
  margin-right: 12px;
}

.menu-item.active {
  background: #ebf5ff;
  color: #3b82f6;
}

.menu-item:hover {
  background: #f8fafc;
}

.badge {
  position: absolute;
  right: 12px;
  background: #ef4444;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

/* 主要内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.selling { background: #ebf5ff; color: #3b82f6; }
.stat-icon.order { background: #f0fdf4; color: #22c55e; }
.stat-icon.wallet { background: #fef3c7; color: #f59e0b; }

.stat-info {
  flex: 1;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-trend {
  font-size: 14px;
}

.stat-trend.up { color: #22c55e; }
.stat-trend.down { color: #ef4444; }

.stat-trend small {
  color: #666;
  margin-left: 4px;
}

.section-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.filter-tabs {
  display: flex;
  gap: 16px;
}

.tab {
  padding: 6px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}
.order-stats-grid {
  display: grid;
  gap: 1.5rem;
  padding: 1.25rem;
}

.order-card {
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  background-color: #fff;
}

.order-id {
  font-size: 1.125rem;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 0.75rem;
}

.order-meta-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
  font-size: 0.9rem;
  color: #555;
}

.status-label {
  color: #27ae60; /* 成功状态绿色，可根据状态值动态切换颜色 */
}
.tab.active {
  background: #3b82f6;
  color: white;
}

.trade-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.trade-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.trade-item:hover {
  background: #f8fafc;
}

.trade-img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.trade-info {
  flex: 1;
}

.trade-info h4 {
  margin-bottom: 8px;
}

.trade-info p {
  color: #666;
  font-size: 14px;
}

.trade-meta {
  text-align: right;
  margin-right: 20px;
}

.trade-price {
  display: block;
  color: #ef4444;
  font-weight: bold;
  margin-bottom: 4px;
}

.trade-time {
  color: #666;
  font-size: 14px;
}

.trade-status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
}

.trade-status.success {
  background: #f0fdf4;
  color: #22c55e;
}

.two-column {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.goods-item {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.goods-item:hover {
  transform: translateY(-4px);
}

.goods-img {
  position: relative;
  height: 160px;
}

.goods-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-status {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  background: #f0fdf4;
  color: #22c55e;
}

.goods-status.hot {
  background: #fef2f2;
  color: #ef4444;
}

.goods-info {
  padding: 12px;
  background: white;
}

.goods-price {
  color: #ef4444;
  margin-top: 8px;
  font-weight: bold;
}

.more-link {
  color: #3b82f6;
  cursor: pointer;
}

.more-link:hover {
  text-decoration: underline;
}
</style>

